package com.github.binarywang.demo.wx.mp.service;


import com.github.binarywang.demo.wx.mp.beans.*;
import com.github.binarywang.demo.wx.mp.config.LsYuFenConfig;
import com.github.binarywang.demo.wx.mp.dto.Result;
import com.github.binarywang.demo.wx.mp.jpa.FocusInfoDao;
import com.github.binarywang.demo.wx.mp.jpa.MerchantsConfigDao;
import com.github.binarywang.demo.wx.mp.utils.FocusUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@ComponentScan(basePackages = "com.github.binarywang.demo.wx.mp.beans.WxMultiConfigDto")
public class FocusInfoService {
    @Autowired
    private FocusInfoDao focusInfoDao;

    @Autowired
    private MerchantsConfigDao merchantsConfigDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private LsYuFenConfig lsYuFenConfig;

    @Autowired
    private Haozhuservice hz;

    public Boolean add(FocusInfo focusInfo){
        focusInfo.setCreateTime(new Date());
        return focusInfoDao.save(focusInfo).getId()>0;
    }

    public FocusInfo getByAppIdAndOpenId(String openId,String appId){
        try{
            return focusInfoDao.findOne(Example.of(FocusInfo.builder()
                .appId(appId)
                .openId(openId)
                .build())).orElse(null);
        }catch(Exception e){
            return null;
        }
    }

    public Result<AdvertMpData> get(List<WxMpUser> user, MeiPaParam param, QrService qrService) {//
        List<WxMultiConfigDto> list = merchantsConfigDao.findAll();
        System.out.println(list);

        log.info("取号参数: {} \n {}", user, param);
        if (user == null) {
            //随机返回即可
            String key = FocusUtils.getPreKey(param);
            log.warn("没有该用户...首次访问....");
            int index = (int) (Math.random() * list.size());
            WxMultiConfigDto config = list.get(index);
            Long Id = hz.getIdbyhaozhuid(config.getHao_zhu_id());
            log.info("=========>>>>Long Id：" + Id);

//            String url = qrService.getQrUrl(config.getAppId(),config.getMerchants().getId());
            String url = qrService.getQrUrl(config.getClient_id(), Id);
            redisService.set(key, param, 120);
            log.info("拿号的key {}", key);
            return Result.success(AdvertMpData.builder()
                .url(url)
                .effective(true)
                .platform("LS_YF")
                .type("QR")
                .data("公众号信息" + config.getName())
                .build());
        }
        log.warn("第二次访问....");

        List<Long> Id2 = user.stream().map(WxMpUser -> WxMpUser.getId()).collect(Collectors.toList());//获取已关注过的Id
        log.info("================>>>>>>>>>>"+Id2);
        list = merchantsConfigDao.findNoAttention(Id2);
        if (CollectionUtils.isEmpty(list)) {//判断公众号是否全部关注
            return Result.success(AdvertMpData.builder()
                .url(null)
                .effective(false)
                .platform("LS_YF")
                .type("QR")
                .data("没有拿到数据噢~")//全部关注没有数据
                .build());
        }else {//放送没关注的公众号
//            String key = FocusUtils.getPreKey(user);
            String key = FocusUtils.getPreKey(param);
            //随机返回即可
            int index = (int)(Math.random() * list.size());
            WxMultiConfigDto config = list.get(index);
            redisService.set(key, param, 120);
            log.info("拿号的key {}", key);
            String hao_zhu_id = config.getHao_zhu_id();
            Long Id3 = hz.getIdbyhaozhuid(hao_zhu_id);
            log.info("=========>>>>Long Id：" + Id3);
//        String url = qrService.getQrUrl(config.getAppId(),config.getMerchants().getId());
            String url = qrService.getQrUrl(config.getClient_id(), Id3);
            if(url==null){
                return Result.error("获取二维码失败");
            }else
                return Result.success(AdvertMpData.builder()
                .url(url)
                .effective(true)
                .platform("LS_YF")
                .type("QR")
                .data("公众号信息" + config.getName())
                .build());
        }
    }
}
